package cn.dakaqi.services.impl;

import cn.dakaqi.dao.GroupMonthDataDao;
import cn.dakaqi.entities.GroupMonthData;
import cn.dakaqi.services.GroupMonthDataService;
import cn.dakaqi.utils.BaseDAO;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/5/18.
 */
@Component(value = "groupMonthDataService")
@Transactional
public class GroupMonthDataServiceImpl implements GroupMonthDataService
{
    @Autowired
    GroupMonthDataDao groupMonthDataDao;
    @Autowired
    BaseDAO baseDAO;

    @Override
    public void save(GroupMonthData groupMonthData) throws ServiceRuntimeException
    {
        groupMonthDataDao.save(groupMonthData);
    }

    @Override
    public void createDefaultData(String groupCode)
    {
        for(int i=6;i>=1;i--)
        {
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MONTH, -i);
            String lastMonth = new SimpleDateFormat("yyyy-MM").format(c.getTime());
            GroupMonthData data = new GroupMonthData();
            data.setActivities(0);
            data.setCreateTime(DateUtil.getToday());
            data.setGroupCode(groupCode);
            data.setMonth(lastMonth);
            data.setTimes(0);
            data.setVolunteers(0);
            this.save(data);
        }
    }

    @Override
    public Page<GroupMonthData> findByGroupCode(String groupCode) throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(0, 12, sort);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("groupCode", new SearchFilter("groupCode", SearchFilter.Operator.EQ, groupCode));
        Specification<GroupMonthData> spec = DynamicSpecifications.bySearchFilter(filters.values(), GroupMonthData.class);
        return this.groupMonthDataDao.findAll(spec, pageRequest);
    }

    /**
     * 每月1日统计社团上一月的新增活动量、人员量、公益时间
     * @throws cn.dakaqi.utils.exception.ServiceRuntimeException
     */
    @Override
    public void statistics() throws ServiceRuntimeException
    {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        String lastMonth = new SimpleDateFormat("yyyy-MM").format(c.getTime());

        String sql = "";


        try
        {
            //查询所有社团
            sql = "select count(ID) as c from U_GROUP where DEL_STATUS = 0";
            List<Map<String,String>> groups = baseDAO.queryNativeSql(sql);
            if(null == groups || groups.size() ==0)
                return;
            int totalNumber = Integer.parseInt(String.valueOf(groups.get(0).get("c")));
            int totalPage = totalNumber/2000+1;
            for(int k=1;k<= totalPage;k++)
            {
                String insertSQL = "insert into  U_GROUP_MONTH_DATA(GROUP_CODE,MONTH,VOLUNTEERS,TIMES,ACTIVITIES,CREATE_TIME) values ";
                StringBuffer sb = new StringBuffer();
                sql = "select ID from U_GROUP where DEL_STATUS = 0";
                sql = "select ID,GROUP_CODE from U_GROUP where DEL_STATUS=0 and ID <= (" + sql + "  order by ID desc limit " + (k - 1) * 2000 + ",1) order by ID desc limit 2000";
                System.out.println(sql);
                groups = baseDAO.queryNativeSql(sql);
                if(null == groups || groups.size() ==0)
                    continue;
                for(Map<String,String> map:groups)
                {
                    int volunteers = 0,times = 0,acts = 0;
                    int GROUP_ID = Integer.parseInt(String.valueOf(map.get("ID")));
                    String GROUP_CODE = map.get("GROUP_CODE");
                    //查询当前社团当月新增志愿者数量
                    sql = "select count(ID) as c from U_GROUP_VOLUNTEER where GROUP_ID = " + GROUP_ID + " and STATUS = " + DKQConstant.APPLY_STATUS_OK;
                    groups = baseDAO.queryNativeSql(sql);
                    if(null != groups && groups.size() > 0)
                    {
                        if(groups.get(0).get("c") != null)
                            volunteers = Integer.parseInt(String.valueOf(groups.get(0).get("c")));
                    }

                    //查询当前社团上一月的所有活动
                    sql = "select count(ID) as c, sum(TIMES) as times from U_ACTIVITY WHERE GROUP_ID = " + GROUP_ID + " and START_TIME like '"+lastMonth+"%' and DEL_STATUS = " + DKQConstant.DEL_NO;
                    groups = baseDAO.queryNativeSql(sql);
                    if(null != groups && groups.size() > 0)
                    {
                        if(groups.get(0).get("c") != null)
                            acts = Integer.parseInt(String.valueOf(groups.get(0).get("c")));
                        if(groups.get(0).get("times") != null)
                            times = Integer.parseInt(String.valueOf(groups.get(0).get("times")));
                    }

                    sb.append("(");
                    sb.append("'");
                    sb.append(GROUP_CODE);
                    sb.append("'");
                    sb.append(",");

                    sb.append("'");
                    sb.append(lastMonth);
                    sb.append("'");
                    sb.append(",");

                    sb.append(volunteers);
                    sb.append(",");

                    sb.append(times);
                    sb.append(",");

                    sb.append(acts);
                    sb.append(",");

                    sb.append("'");
                    sb.append(DateUtil.getToday());
                    sb.append("'");


                    sb.append(")");
                    sb.append(",");
                }

                if(sb.toString().length() > 1)
                {
                    insertSQL = insertSQL + sb.toString().substring(0,sb.toString().length()-1);
                    baseDAO.updateNativeSql(insertSQL);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
